package x.ovo.wechat.bot.plugin;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.ds.GlobalDSFactory;
import cn.hutool.db.nosql.redis.RedisDS;
import cn.hutool.setting.Setting;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import x.ovo.wechat.bot.core.command.CommandExcutor;
import x.ovo.wechat.bot.core.event.EventListener;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.io.File;
import java.io.InputStream;

@Getter
@Slf4j(topic = "StatisticsPlugin")
public class StatisticsPlugin extends Plugin {

    private RedisDS ds;

    @Override
    public void onLoad() {
        File redisSettingFile = FileUtil.file(this.getDataDir(), "redis.setting");
        File dbSsettingFile = FileUtil.file(this.getDataDir(), "db.setting");
        File dbFile = FileUtil.file(this.getDataDir(), "statistics.db");
        if (!FileUtil.exist(dbSsettingFile)) {
            InputStream stream = this.getClassLoader().getResourceAsStream("db.setting");
            IoUtil.copy(stream, FileUtil.getOutputStream(dbSsettingFile));
        }
        if (!FileUtil.exist(dbFile)) {
            InputStream stream = this.getClassLoader().getResourceAsStream("statistics.db");
            IoUtil.copy(stream, FileUtil.getOutputStream(dbFile));
        }
        if (!redisSettingFile.exists()) {
            InputStream stream = this.getClass().getClassLoader().getResourceAsStream("redis.setting");
            IoUtil.copy(stream, FileUtil.getOutputStream(redisSettingFile));
        }

        Setting setting = new Setting(dbSsettingFile.getAbsolutePath());
        DSFactory factory = DSFactory.create(setting);
        GlobalDSFactory.set(factory);
        log.debug("load db setting success, from: {}, config: {}", dbSsettingFile.getAbsolutePath(), setting.getSetting(null));

        // 读取外部的redis配置
        this.ds = RedisDS.create(new Setting(redisSettingFile, Setting.DEFAULT_CHARSET, false), null);
        log.debug("redis ping: {}", this.ds.getJedis().ping());
    }

    @Override
    public EventListener<?, ?> getEventListener() {
        return new StatisticsListener(this, this.ds);
    }

    @Override
    public CommandExcutor getCommandExcutor() {
        return new StatisticsExecutor(this);
    }
}
